package com.tanhua.server.service;

import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.domain.vo.NearUserVo;
import com.tanhua.domain.vo.UserLocationVo;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.LocationApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 搜附近业务逻辑处理层
 */
@Service
public class LocationService {
    @Reference
    private LocationApi locationApi;

    @Reference
    private UserInfoApi userInfoApi;

    /**
     * 上报地理位置
     * GeoJsonPoint:没有实现序列化
     * @param latitude 纬度
     * @param longitude 经度
     * @param addrStr 地理位置中文信息
     */
    public void saveUpdateLocation(Double latitude, Double longitude, String addrStr) {
        locationApi.saveUpdateLocation(latitude,longitude,addrStr, UserHolder.getUserId());
    }

    /**
     * 搜附近
     * gender：性别 （非必须） 男
     * distance: 传入的值为空 则为2000米
     */
    public List<NearUserVo> searchNearUser(String gender, String distance) {
        Long userId = UserHolder.getUserId();
        //a.调用服务根据当前用户位置、搜索距离  查询附近用户List<UserLocationVo>
        List<UserLocationVo> userLocationList = locationApi.searchNearUser(userId,Long.valueOf(distance));
        if(CollectionUtils.isEmpty(userLocationList)){
            return null;
        }
        ///b.循环遍历查询UserInfo
        List<NearUserVo> nearUserVoList = new ArrayList<>();
        for (UserLocationVo userLocation : userLocationList) {
            NearUserVo nearUserVo = new NearUserVo();

            Long nearUserId = userLocation.getUserId();// 附近用户id
            //c.将当前用户过滤掉
            if(userId.equals(nearUserId)){
                continue;
            }
            UserInfo userInfo = userInfoApi.queryUserInfo(nearUserId);
            //d.将性别不符合过滤掉
            //传入的gender：需要的搜索的性别   userInfo.getGender():数据库查询用户性别
            if(!StringUtils.isEmpty(gender) && !gender.equals(userInfo.getGender())){
                continue;
            }

            //将符合要求的数据封装
            nearUserVo.setUserId(nearUserId);//附近用户id
            nearUserVo.setNickname(userInfo.getNickname());//昵称
            nearUserVo.setAvatar(userInfo.getAvatar());//头像
            nearUserVoList.add(nearUserVo);
        }
        //e.封装Vo返回（附近用户id 昵称 头像）
        return nearUserVoList;
    }
}
